package org.gaaidou.ptarmigan.springboot.distributed;

import java.util.concurrent.locks.Lock;
import java.util.function.Supplier;


public interface DistributedLock {

    public Lock create(String resource, int lockTimeoutSecond);

    public Lock create(String resource);

    default void exec(String resource, Runnable runnable) {
        exec(resource, 20, runnable);
    }

    default void exec(String resource, int lockTimeoutSecond, Runnable runnable) {
        Lock lock = create(resource, lockTimeoutSecond);
        if (lock.tryLock()) {
            try {
                runnable.run();
            } finally {
                lock.unlock();
            }
        }

    }

    default <T> T exec(String resource, Supplier<T> supplier) {
        return exec(resource, 20, supplier);
    }

    default <T> T exec(String resource, int lockTimeoutSecond, Supplier<T> supplier) {
        Lock lock = create(resource, lockTimeoutSecond);
        if (lock.tryLock()) {
            try {
                return supplier.get();
            } finally {
                lock.unlock();
            }
        }
        return null;
    }
}
